package com.aiti.lulian.controller;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CardVisitorRecordDto;
import com.aiti.lulian.entity.CardHolder;
import com.aiti.lulian.entity.CardVisitorRecord;
import com.aiti.lulian.entity.excel.CardVisitorRecordExport;
import com.aiti.lulian.handler.HeaderStyleHandler;
import com.aiti.lulian.service.CardHolderService;
import com.aiti.lulian.service.ICardVisitorRecordService;
import com.aiti.lulian.vo.CardVisitorRecordVo;
import com.aiti.lulian.vo.UserIdAndUserName;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "名片访客记录控制层")
@RestController
@RequestMapping("/visitor")
public class CardVisitorRecordController extends WebController {

    @Autowired
    private ICardVisitorRecordService cardVisitorRecordService;

    @Autowired
    private CardHolderService cardHolderService;

    /**
     * @param cardId 受访用户名片ID
     * @return
     */
    @ApiOperation("查询我的访客信息列表")
    @GetMapping("/list")
    public Message queryMyVisitorList(@RequestParam("cardId") String cardId){
        try {
            return Success(cardVisitorRecordService.queryMyVisitorList(cardId));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    /**
     * @param cardId 我的名片ID
     * @return
     */
    @ApiOperation("查询我看过的名片信息列表")
    @GetMapping("/visitedList")
    public Message queryMyVisitedList(@RequestParam("cardId") String cardId){
        try {
            return Success(cardVisitorRecordService.queryMyVisitedList(cardId));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation("查询访客信息详情")
    @GetMapping("/{baseId}")
    public Message queryVisitorDetail(@PathVariable("baseId") String baseId){
        CardVisitorRecordVo cardVisitorRecordVo = cardVisitorRecordService.queryVisitorDetail(baseId);
        return Success(cardVisitorRecordVo);
    }

    @GetMapping("/getVisitorRecords/{userId}")
    public Message getVisitorRecords(@PathVariable("userId") String userId) {
        List<UserIdAndUserName> visitorRecords = cardVisitorRecordService.getVisitorRecords(userId);

        return Message.success(visitorRecords);
    }

    @ApiOperation("编辑访客备注")
    @PutMapping("/remarks")
    public Message editVisitorRemarks(@RequestBody CardVisitorRecordDto dto) {
        String currentUserId = dto.getCurrentUserId();
        if (StrUtil.isBlank(currentUserId)) {
            currentUserId = findUserId();
            if (StrUtil.isBlank(currentUserId)) {
                return Fail("请先登录");
            }
            dto.setCurrentUserId(currentUserId);
        }
        return cardVisitorRecordService.editVisitorRemarks(dto);
    }

    @ApiOperation("更新访客记录中名片交换状态")
    @PutMapping("/exchangeStatus")
    public Message updateExchangeStatus(@RequestBody CardVisitorRecordDto dto) {
        String userId = dto.getUserId();
        String visitorId = dto.getVisitorId();
        String exchangeStatus = dto.getExchangeStatus();
        if (StrUtil.equals(exchangeStatus, "2")) {
            CardVisitorRecord one1 = cardVisitorRecordService.getOne(new LambdaQueryWrapper<CardVisitorRecord>().eq(CardVisitorRecord::getUserId, userId).eq(CardVisitorRecord::getVisitorId, visitorId));
            if (one1 == null) {
                return Success();
            }
            CardVisitorRecord one2 = cardVisitorRecordService.getOne(new LambdaQueryWrapper<CardVisitorRecord>().eq(CardVisitorRecord::getUserId, visitorId).eq(CardVisitorRecord::getVisitorId, userId));
            if (one2 != null) {
                updateExchangeStatusCommon(visitorId, userId, exchangeStatus);
            }
        }
        updateExchangeStatusCommon(userId, visitorId, exchangeStatus);
        return Success();
    }

    private void updateExchangeStatusCommon(String userId, String visitorId, String exchangeStatus) {
        LambdaUpdateWrapper<CardVisitorRecord> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CardVisitorRecord::getUserId, userId)
                .eq(CardVisitorRecord::getVisitorId, visitorId)
                .set(CardVisitorRecord::getExchangeStatus, exchangeStatus);
        cardVisitorRecordService.update(updateWrapper);
    }

    /**
     * 处理名片交换功能面临的历史存在单方面收藏的问题
     * 即如果对方单方面收藏了自己，但自己没有收藏对方，那么此时发出的名片交换请求实则可以作为单方面收藏对方进行处理
     */
    @ApiOperation("判断本次名片交换请求是否当作单方面收藏对方进行处理")
    @GetMapping("/isUnilateral")
    public Message isUnilateral(CardVisitorRecordDto dto) {
        String userId = dto.getUserId();
        String visitorId = dto.getVisitorId();
        List<CardHolder> list = cardHolderService.list(new LambdaQueryWrapper<CardHolder>().eq(CardHolder::getCardHolderUserId, userId).eq(CardHolder::getBaseUserId, visitorId));
        if (list.size() > 0) {
            CardHolder cardHolder = new CardHolder();
            cardHolder.setCardHolderUserId(visitorId);
            cardHolder.setBaseUserId(userId);
            cardHolder.setBaseCreateTime(new Date());
            cardHolderService.save(cardHolder);
            cardVisitorRecordService.update(new LambdaUpdateWrapper<CardVisitorRecord>().eq(CardVisitorRecord::getBaseId, dto.getBaseId()).set(CardVisitorRecord::getExchangeStatus, "2"));
            return Success(true);
        }
        return Success(false);
    }

    @ApiOperation(value = "设置登录但没名片访客的手机号")
    @PutMapping("setContactNumber")
    public Message setContactNumber(@RequestBody CardVisitorRecordDto dto){
        return cardVisitorRecordService.setContactNumber(dto);
    }

    /**
     * 同步对于通过快捷登录但尚未使用名片的微信访客在开始使用名片后对应访客记录的信息
     */
    @ApiOperation(value = "同步对应访客记录的信息")
    @PutMapping("updateNotLoginRecord")
    public Message updateNotLoginRecord(@RequestBody CardVisitorRecordDto dto){
        return cardVisitorRecordService.updateNotLoginRecord(dto);
    }

    @ApiOperation(value = "访问名片")
    @PostMapping("/visit-card")
    public void visitCard(@RequestBody CardVisitorRecordDto dto){
        cardVisitorRecordService.visitCard(dto);
    }

    @ApiOperation("查询访客信息列表（分数据权限）")
    @GetMapping("/record/list")
    public Message queryVisitorList(@RequestParam("userId") String userId,
                                    @RequestParam("enterpriseId") String enterpriseId,
                                    @RequestParam("pageNum") Integer pageNum,
                                    @RequestParam("pageSize") Integer pageSize,
                                    @RequestParam(value = "realname", required = false) String realname,
                                    @RequestParam(value = "enterpriseName", required = false) String enterpriseName,
                                    @RequestParam(value = "visitedRealname", required = false) String visitedRealname,
                                    @RequestParam(value = "condition", required = false) String condition){
        try {
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            Page<CardVisitorRecord> page = startPage(pageNum, pageSize);
            List<CardVisitorRecordVo> cardVisitorRecordVos = cardVisitorRecordService.queryVisitorList(userId, enterpriseId, realname, enterpriseName, visitedRealname, condition, page);
            return Success(getPageResult(cardVisitorRecordVos, pageNum, pageSize, page.getTotal()));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    /**
     * 新版名片小程序
     */
    @ApiOperation("后台查询访客信息列表")
    @GetMapping("/list-backend")
    public Message queryVisitorListBackend(CardVisitorRecordDto dto){
        Page<CardVisitorRecord> page = startPage(dto);
        List<CardVisitorRecordVo> list = cardVisitorRecordService.queryVisitorListBackend(dto, page);
        return Message.success(getPageResult(list, dto.getPageNum(), dto.getPageSize(), page.getTotal()));
    }

    /**
     * 新版名片小程序
     */
    @ApiOperation("后台导出访客信息列表")
    @GetMapping("/list-backend/export")
    public void exportVisitorListBackend(HttpServletResponse response, CardVisitorRecordDto dto) throws IOException {
        List<CardVisitorRecordVo> list = cardVisitorRecordService.queryVisitorListBackend(dto, null);
        List<CardVisitorRecordExport> visitorRecordExportList = list.stream().map(i -> {
            CardVisitorRecordExport cardVisitorRecordExport = new CardVisitorRecordExport();
            BeanUtils.copyProperties(i, cardVisitorRecordExport);
            cardVisitorRecordExport.setNumber(list.indexOf(i) + 1);
            return cardVisitorRecordExport;
        }).collect(Collectors.toList());

        // 设置响应头，确保浏览器以下载方式处理文件
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置文件名，注意需要对中文进行 URL 编码
        String fileName = URLEncoder.encode("访客数据列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + ".xlsx\";" + " filename*=UTF-8''" + fileName + ".xlsx");

        // 使用 EasyExcel 写入数据到输出流
        OutputStream outputStream =  response.getOutputStream();
        EasyExcel.write(outputStream, CardVisitorRecordExport.class)
                .sheet("访客数据列表")
                .registerWriteHandler(new HeaderStyleHandler())
                .doWrite(visitorRecordExportList);

        // 关闭流资源
        if (outputStream != null) {
            outputStream.close();
        }
    }

//    @ApiOperation("发送来自于小程序的访客提示服务消息")
//    @GetMapping("/sendTip/fromMiniProgram")
//    public Message sendTipFromMiniProgram(@RequestParam("") String ) {
//        List<UserIdAndUserName> visitorRecords = cardVisitorRecordService.getVisitorRecords(userId);
//
//        return Message.success(visitorRecords);
//    }
}